<template>
  <div>
    <a-modal class="form1"
             v-model="dialogVisible"
             title="默认联系人"
             width="800px"
             :dialog-style="{ top: '15vh' }"
             ok-text="确认"
             cancel-text="取消"
             @ok="handleOk()"
             @cancel="cancelOK()">
      <a-form-model ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="姓名"
                               style=""
                               prop="contactName">
              <a-input v-model="form.contactName"
                       placeholder="请输入姓名" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="系统消息"
                               style=""
                               prop="receiveSysMsg">
              <a-radio-group v-model="form.receiveSysMsg"
                             @change="onChangeSex">
                <a-radio v-for="item in sexArr "
                         :key="item.id"
                         :value="item.type"> {{item.title}} </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="邮箱"
                               style=""
                               prop="contactEmail">
              <a-input v-model="form.contactEmail"
                       placeholder="请输入邮箱" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="手机号码"
                               style=""
                               prop="contactMobile">
              <a-input v-model="form.contactMobile"
                       placeholder="请输入手机号" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="地址"
                               prop="optionsA">
              <a-cascader :options="CityArray"
                          :value="form.optionsA"
                          :load-data="loadData"
                          change-on-select
                          @change="onChangeAddress"
                          placeholder="请选择地址" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="详细地址"
                               style=""
                               prop="detailAddr">
              <a-input v-model="form.detailAddr"
                       placeholder="请输入详细地址" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-row>
              <a-col :span="7"></a-col>
              <a-col :span="14">
                <a-checkbox :checked="form.beDefault"
                            @change="onChangeBeDefault">
                  默认联系人
                </a-checkbox>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import '@/assets/css/form.less'
export default {
  name: 'UserEditForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      contactSaveDTOS: '',
      // true 新建 false 修改
      clickStatus: true,
      CityArray: [],
      //选中的详细地址list
      selectAddressArr: [],
      //api地区数据
      apiData: {},
      //api默认选中地址
      apiAddress: {},
      form: {
        detailAddr: '',
        optionsA: [],

        //省
        province: "",
        //省编码
        provinceCode: "",
        //市
        city: "",
        //市编码
        cityCode: "",
        //区
        district: "",
        //区编码
        districtCode: "",
        //街道
        street: "",
        //街道编码
        streetCode: "",


        //姓名
        contactName: '',
        //性别
        receiveSysMsg: true,
        sexName: '',
        //邮箱
        contactEmail: '',
        //手机号码
        contactMobile: '',
        //证件类型
        cardType: undefined,
        //证件号码
        cardNo: '',
        // 部门
        department: '',
        //职位
        position: '',
        //固定电话固定
        telephone: '',
        //备注
        comment: '',
        // 默认联系人
        beDefault: true,
      },
      //性别
      sexArr: [
        {
          title: '不接收',
          type: false,
        },
        {
          title: '接收',
          type: true,
        },
      ],
      cardTypeArr: [
        {
          title: '身份证',
          type: '01',
        },
        {
          title: '护照',
          type: '02',
        },
        {
          title: '军官证',
          type: '03',
        },
        {
          title: '港澳通行证',
          type: '04',
        },
        {
          title: '台胞证',
          type: '05',
        },
      ],
      //
      rules: {
        contactName: [{ required: true, message: '请输入姓名' }],
        receiveSysMsg: [{ required: true, message: '请选择是否接收系统消息' }],
        contactEmail: [{ required: true, message: '请输入邮箱' }, { pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, message: '请输入正确的邮箱' }],
        contactMobile: [{ required: true, message: '请输入手机号' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }],
        optionsA: [{ required: true, message: "请选择所在区域" }],
        detailAddr: [{ required: true, message: "请输入详细地址" }],
        // cardType: [{ required: true, message: '请选择证件类型' }],
        // cardNo: [{ required: true, message: '请输入证件号码' }],
        // department: [{ required: true, message: '请输入部门' }],
        // position: [{ required: true, message: '请输入职位' }],
        // telephone: [{ required: false, message: '请输入固定电话' }, { pattern: /^0\d{2,3}-?\d{7,8}$/, message: "请输入正确固定电话", },],
      },
      dialogVisible: false
    }
  },
  mounted () {
    this.getCity();
  },
  methods: {
    //获取列表
    contactSavedtos (contactSaveDTOS) {
      this.contactSaveDTOS = contactSaveDTOS || []
      this.clickStatus = true
    },
    //修改编辑联系人
    getList (item) {
      this.form = JSON.parse(JSON.stringify(item));
      if (!item.optionsA) {
        this.getselectList(item)
        this.setApiAddress(item)
      }
      this.clickStatus = false
    },
    setApiAddress (item) {
      console.log(item, '123123');
      this.apiAddress.province = item.provinceCode
      this.apiAddress.city = item.cityCode
      this.apiAddress.district = item.districtCode
    },
    //获取选中省市区的详情
    getselectList (result) {
      // console.log(result.tenantInvoice);
      console.log(result);
      let requestData = {
        district: result.districtCode,
        city: result.cityCode,
        province: result.provinceCode,
      };
      for (let i in requestData) {
        this.apiRequest(requestData[i], i, result);
      }
    },
    apiRequest (code, type, result) {
      console.log(code, type, 'a1');
      this.$store
        .dispatch("unSave/getAreaListSync", {
          code,
          level: type
        })
        .then((res) => {
          console.log(123123);
          this.apiData[type] = res
          this.apiCallBack(result);
        });
    },
    apiCallBack (result) {
      console.log(this.apiData)
      if (Object.keys(this.apiData).length === 3) {
        let districtData = this.formatOptions(this.apiData.district);
        let cityData = this.formatOptions(this.apiData.city);
        cityData = this.addChildren(
          cityData,
          this.apiAddress.district,
          districtData
        );
        let provinceData = this.formatOptions(this.apiData.province);
        provinceData = this.addChildren(
          provinceData,
          this.apiAddress.city,
          cityData
        );

        let options = this.CityArray;
        options = this.addChildren(
          options,
          this.apiAddress.province,
          provinceData
        );
        this.CityArray = [...options];
        let optionsA = [];
        optionsA.push(result.provinceCode);
        optionsA.push(result.cityCode);
        optionsA.push(result.districtCode);
        optionsA.push(result.streetCode);
        this.$set(this.form, 'optionsA', optionsA);

        console.log(this.form.optionsA);
      }
    },
    addChildren (options, code, childrenData) {
      options.forEach((element) => {
        if (element.code === code) {
          element.children = childrenData;
        }
      });
      return options;
    },
    formatOptions (array) {
      array.map(function (value) {
        value.label = value.name;
        value.value = value.code;
        return value;
      });
      return array;
    },

    //性别选择
    onChangeSex (e) {
      this.form.sexName = e.target.value === 0 ? '男' : '女'
    },
    //获取省市区 如果存的没有就走接口获取再存起来 如果有就直接拿存的赋值
    getCity () {
      console.log('a2')
      this.$store.dispatch("unSave/getAreaListSync", {}).then((result) => {
        for (let i = 0; i < result.length; i++) {
          result[i].isLeaf = false;
          result[i].label = result[i].name;
          result[i].value = result[i].code;
          delete result[i].children;
          this.$set(result[i], 'isChecked', false);
        }
        this.CityArray = result;
        this.servicesArea = result.length > 0 ? JSON.parse(JSON.stringify(result)) : [];
      });
    },
    loadData (selectedOptions) {
      this.selectAddressArr = selectedOptions;
      const targetOption = selectedOptions[selectedOptions.length - 1];
      if (targetOption.level !== "street") {
        targetOption.loading = true;
        console.log(targetOption.code, targetOption.level, 'a3')
        this.$store
          .dispatch("unSave/getAreaListSync", {
            code: targetOption.code,
            level: targetOption.level,
          })
          .then((res) => {
            let result = res;
            for (let i = 0; i < result.length; i++) {
              result[i].isLeaf = result[i].level === "street";
              result[i].label = result[i].name;
              result[i].value = result[i].code;
              delete result[i].children;
            }
            console.log(result);
            targetOption.children = result;
            if (result.length === 0) {
              targetOption.isLeaf = true;
            }
            targetOption.loading = false;
            this.CityArray = [...this.CityArray];
          });
      }
    },
    onChangeAddress (val) {
      if (val.length === 0) {
        this.addressArr();
      }
      for (let i = 0; i < this.selectAddressArr.length; i++) {
        if (this.selectAddressArr[i].level === "province") {
          this.form.province = this.selectAddressArr[i].label;
          this.form.provinceCode = this.selectAddressArr[i].value;
        }
        if (this.selectAddressArr[i].level === "city") {
          this.form.city = this.selectAddressArr[i].label;
          this.form.cityCode = this.selectAddressArr[i].value;
        }
        if (this.selectAddressArr[i].level === "district") {
          this.form.district = this.selectAddressArr[i].label;
          this.form.districtCode = this.selectAddressArr[i].value;
        }
      }
      if (val.length === 4) {
        console.log('a4')
        this.$store
          .dispatch("unSave/getAreaListSync", {
            code: this.form.districtCode,
            level: this.form.district,
          })
          .then((data) => {
            for (let i = 0; i < data.length; i++) {
              if (data[i].value === val[3]) {
                this.form.street = data[i].name;
                this.form.streetCode = data[i].value;
                this.form.optionsA = val;
                this.$forceUpdate();
              }
            }
          });
      }
    },



    //是否默认联系人
    onChangeBeDefault (e) {
      console.log(e, 'eeee');
      console.log(this.form.beDefault, 'this.form.beDefault')
      console.log(this.contactSaveDTOS, 'this.contactSaveDTOS');
      if (!this.form.beDefault) {
        this.form.beDefault = e.target.checked
      }
      if (this.contactSaveDTOS !== null) {
        if (this.contactSaveDTOS.length !== 0 && this.clickStatus === true) {
          this.form.beDefault = e.target.checked
        }
      }

    },

    //确定新增
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log(this.form);
          this.$emit('confirmLinkman', JSON.parse(JSON.stringify(this.form)));
          this.concel()
        }
      });
    },
    //取消新增 如果form表单没值就是第一次新增 有值就是取消修改取消新增
    cancelOK () {
      this.$emit('cancel')
      this.concel()
    },
    //表单清空
    concel () {
      this.$refs.ruleForm.resetFields();
      this.form.contactName = ''
      this.form.contactEmail = ''
      this.form.contactMobile = ''
      this.form.detailAddr = ''
      this.form.comment = ''
      this.form.beDefault = true
    }
  },
  watch: {
    visible (newVal) {
      this.dialogVisible = newVal;
    }
  }
}
</script>
<style lang="less" scoped>
.drawerForm {
  padding: 20px 20px 80px 30px;
  overflow: hidden;
}
/deep/ .ant-form-explain {
  position: absolute;
}
/deep/ .ant-form-item-label > label {
  color: @colorGreyFont;
  font-size: 12px;
  font-family: PingFangSC, PingFangSC-Regular;
}
/deep/ .ant-form label {
  font-size: 12px;
  color: @colorGreyFont;
}
/deep/ .ant-input {
  color: @colorCommonFont;
  width: 240px;
}
/deep/ .ant-input::placeholder {
  color: #ccc;
}
/deep/ .ant-form-item {
  font-size: 12px;
}
</style>
